package com.jyw.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.jyw.common.constant.UserConstants;
import com.jyw.common.utils.DateUtils;
import com.jyw.system.domain.SysConfig;
import com.jyw.system.domain.vo.SysBigScreenConfigVo;
import com.jyw.system.enums.OtherConfigEnum;
import com.jyw.system.service.ISysBigScreenConfigService;
import com.jyw.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Created by ZhangCheng on 2023/08/15  (系统大屏配置)
 */
@Service
public class SysBigScreenConfigServiceImpl implements ISysBigScreenConfigService {

    @Autowired
    private ISysConfigService sysConfigService;

    @Override
    public SysBigScreenConfigVo getConfig() {
        SysConfig sysConfig = sysConfigService.findConfigByKey(OtherConfigEnum.BIG_SCREEN.getKey());
        if (sysConfig != null && StrUtil.isNotEmpty(sysConfig.getConfigValue())) {
            return JSONObject.parseObject(sysConfig.getConfigValue(), SysBigScreenConfigVo.class);
        }
        return null;
    }

    @Override
    public SysBigScreenConfigVo getDefaultConfig() {
        SysBigScreenConfigVo configVo=getConfig();
        if(configVo!=null){
            return configVo;
        }
        return new SysBigScreenConfigVo();
    }

    @Override
    public void updateBigScreenConfig(SysBigScreenConfigVo sysBigScreenConfigVo) {
        SysConfig sysConfig = sysConfigService.findConfigByKey(OtherConfigEnum.BIG_SCREEN.getKey());
        String configValue = JSONObject.toJSONString(sysBigScreenConfigVo);
        if (sysConfig != null) {
            sysConfig.setConfigValue(configValue);
            sysConfig.setUpdateTime(DateUtils.getNowDate());
            sysConfigService.updateConfig(sysConfig);
        } else {
            initConfig(configValue);
        }
    }

    /**
     * 初始化配置数据
     *
     * @param configValue
     */
    private void initConfig(String configValue) {
        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigKey(OtherConfigEnum.BIG_SCREEN.getKey());
        sysConfig.setConfigName(OtherConfigEnum.BIG_SCREEN.getName());
        sysConfig.setConfigValue(configValue);
        sysConfig.setConfigType(UserConstants.YES);
        sysConfig.setCreateTime(DateUtils.getNowDate());
        sysConfigService.insertConfig(sysConfig);
    }
}
